package xyz.naokeziteng.data_structure.graph_theory;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author hawk
 * @date 2022/10/8
 * @desc 图的深度优先遍历-联通分量
 **/
public class GraphDFSCC {

    private Graph G;
    private int[] visited;
    //联通分量(connected component)
    private int ccount = 0;


    public GraphDFSCC(Graph G) {
        this.G = G;
        this.visited = new int[G.V()];
        Arrays.fill(visited, -1);
        for (int v = 0; v < G.V(); v++) {
            if (visited[v] == -1) {
                dfs(v, ccount);
                ccount++;
            }
        }
    }

    //深度优先遍历
    private void dfs(int v, int ccid) {
        visited[v] = ccid;
        for (int w : G.adj(v)) {
            if (visited[w] == -1) {
                dfs(w, ccid);
            }
        }
    }

    //联通分量
    public int ccount() {
        for (int e : visited) {
            System.out.print(e + " ");
        }
        System.out.println();
        return ccount;
    }

    public boolean isConnected(int v, int w) {
        G.validateVertex(v);
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    public ArrayList<Integer>[] components() {
        ArrayList<Integer>[] res = new ArrayList[ccount];
        for (int i = 0; i < ccount; i++) {
            res[i] = new ArrayList<>();
        }
        for (int i = 0; i < G.V(); i++) {
            res[visited[i]].add(i);
        }
        return res;
    }


    public static void main(String[] args) {
        GraphDFSCC adjacencyMatrix = new GraphDFSCC(new Graph("src/main/resources/g.txt"));
        System.out.println(adjacencyMatrix.ccount());
        System.out.println(adjacencyMatrix.isConnected(0, 6));
        System.out.println(adjacencyMatrix.isConnected(0, 5));
        ArrayList<Integer>[] comp = adjacencyMatrix.components();
        for(int ccid = 0;ccid < comp.length;ccid ++) {
            System.out.print(ccid +": ");
            System.out.println(comp[ccid]);
        }
    }
}
